<?php
namespace App\Library\System;

use Zend\Db\Adapter\Adapter;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\Sql\Sql as SqlConnection;

class Sql
{

    public $sql;

    public function __construct()
    {
        $config = Config::getInstance();
        $mysql = $config->mysql;
        $server = $config->app->server;

        $this->adapter = new Adapter(array(
            'driver'         => $mysql->driver,
            'host'           => $mysql->$server->host,
            'port'           => $mysql->$server->port,
            'database'       => $mysql->$server->database,
            'username'       => $mysql->$server->user,
            'password'       => $mysql->$server->password,
            'driver_options' => array(
                \PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
            ),
        ));

        $this->sql = null;

        try {
            $this->sql = new SqlConnection($this->adapter);
        } catch (Exception $e) {
            die($e);
        }

    }

    private static $static_sql;

    public static function getInstance()
    {
        if (!self::$static_sql) {
            self::$static_sql = new Sql();
        }

        return self::$static_sql;
    }

    public function run($sql, $type)
    {
        try {
            $statement = $this->sql->prepareStatementForSqlObject($sql);
        } catch (\Exception $e) {
            echo $e;
        }

        $resultSet = null;

        if ($type > 0) {
            $resultSet = new ResultSet();
            $resultSet->initialize($statement->execute());
        } else {
            $statement->execute();

            return;
        }

        if ($type == 1) {
            return $resultSet->current();
        }

        $resultSet->buffer();

        return $resultSet;
    }

}